package com.example.home.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.PopupMenu
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.home.entity.VideoIdEntity
import com.example.home.R
import com.example.image.GlideUtils

/**
 * 视频列表适配器，用于在 RecyclerView 中展示视频信息
 *
 * @param videoList 视频数据列表，每个元素为 VideoIdEntity 类型
 * @param onVideoClick 视频项点击事件回调函数，默认为空实现
 */
class VideoAdapter(
    private val videoList: List<VideoIdEntity>,
    private val onVideoClick: (VideoIdEntity) -> Unit = {}
) : RecyclerView.Adapter<VideoAdapter.VideoViewHolder>() {

    // 用于跟踪点赞和收藏状态的集合
    private val likedVideos = mutableSetOf<Int>()
    private val favoritedVideos = mutableSetOf<Int>()

    /**
     * 视频项的 ViewHolder，持有 item_video 布局中的各个控件引用
     */
    inner class VideoViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val coverImageView: ImageView = itemView.findViewById(R.id.iv_cover)
        val durationTextView: TextView = itemView.findViewById(R.id.tv_duration)
        val titleTextView: TextView = itemView.findViewById(R.id.tv_title)
        val avatarImageView: ImageView = itemView.findViewById(R.id.iv_head)
        val publisherTextView: TextView = itemView.findViewById(R.id.tv_name)
        val likeTextView: TextView = itemView.findViewById(R.id.dz)
        val favoriteTextView: TextView = itemView.findViewById(R.id.sc)
        val likeImageView: ImageView = itemView.findViewById(R.id.iv_dianzan)
        val favoriteImageView: ImageView = itemView.findViewById(R.id.iv_shoucang)
        val pointImageView: ImageView = itemView.findViewById(R.id.iv_point)
    }

    /**
     * 创建 ViewHolder 实例，加载 item_video 布局
     *
     * @param parent 父容器 ViewGroup
     * @param viewType 视图类型（本适配器未使用）
     * @return 新创建的 VideoViewHolder 实例
     */
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VideoViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_video, parent, false)
        return VideoViewHolder(view)
    }

    /**
     * 绑定数据到 ViewHolder，设置视频项的显示内容和点击事件
     *
     * @param holder 当前项的 ViewHolder
     * @param position 当前项在列表中的位置
     */
    override fun onBindViewHolder(holder: VideoViewHolder, position: Int) {
        val video = videoList[position]

        // 加载视频封面图片
        GlideUtils.loadImage(
            holder.itemView.context,
            video.videomainimag,
            holder.coverImageView
        )

        // 设置视频标题
        holder.titleTextView.text = video.title

        // 加载发布者头像
        Glide.with(holder.itemView.context)
            .load(video.avatar_url)
            .placeholder(R.drawable.head_portrait)
            .into(holder.avatarImageView)

        // 设置发布者名称
        holder.publisherTextView.text = video.name

        // 设置播放数（获取channelid前三位）
        holder.likeTextView.text = formatCount(extractFirstFourDigits(video.channelid))

        // 设置评论数（获取channelid后三位）
        holder.favoriteTextView.text = formatCount(extractLastFourDigits(video.channelid))

        // 设置视频时长（硬编码示例）
        holder.durationTextView.text = "05:42"

        // 设置点赞状态
        updateLikeState(holder, video.id)

        // 设置收藏状态
        updateFavoriteState(holder, video.id)

        // 设置点赞图标点击事件
        holder.likeImageView.setOnClickListener {
            toggleLike(holder, video)
        }

        // 设置收藏图标点击事件
        holder.favoriteImageView.setOnClickListener {
            toggleFavorite(holder, video)
        }

        // 设置更多选项图标点击事件
        holder.pointImageView.setOnClickListener {
            showPopupMenu(holder.pointImageView, video)
        }

        // 设置视频项点击事件
        holder.itemView.setOnClickListener {
            onVideoClick(video)
        }
    }

    /**
     * 更新点赞状态显示
     */
    private fun updateLikeState(holder: VideoViewHolder, videoId: Int) {
        if (likedVideos.contains(videoId)) {
            holder.likeImageView.setImageResource(R.drawable.ic_live_hong)
            // 增加点赞数
            val currentCount = holder.likeTextView.text.toString()
            val count = parseCount(currentCount) + 1
            holder.likeTextView.text = formatCount(count)
        } else {
            holder.likeImageView.setImageResource(R.drawable.ic_live_hui)
            // 减少点赞数
            val currentCount = holder.likeTextView.text.toString()
            val count = parseCount(currentCount).coerceAtLeast(1) - 1
            holder.likeTextView.text = formatCount(count)
        }
    }

    /**
     * 更新收藏状态显示
     */
    private fun updateFavoriteState(holder: VideoViewHolder, videoId: Int) {
        if (favoritedVideos.contains(videoId)) {
            holder.favoriteImageView.setImageResource(R.drawable.ic_shoucangyellow)
            // 增加收藏数
            val currentCount = holder.favoriteTextView.text.toString()
            val count = parseCount(currentCount) + 1
            holder.favoriteTextView.text = formatCount(count)
        } else {
            holder.favoriteImageView.setImageResource(R.drawable.ic_sc_hui)
            // 减少收藏数
            val currentCount = holder.favoriteTextView.text.toString()
            val count = parseCount(currentCount).coerceAtLeast(1) - 1
            holder.favoriteTextView.text = formatCount(count)
        }
    }

    /**
     * 切换点赞状态
     */
    private fun toggleLike(holder: VideoViewHolder, video: VideoIdEntity) {
        if (likedVideos.contains(video.id)) {
            likedVideos.remove(video.id)
        } else {
            likedVideos.add(video.id)
        }
        updateLikeState(holder, video.id)
    }

    /**
     * 切换收藏状态
     */
    private fun toggleFavorite(holder: VideoViewHolder, video: VideoIdEntity) {
        if (favoritedVideos.contains(video.id)) {
            favoritedVideos.remove(video.id)
        } else {
            favoritedVideos.add(video.id)
        }
        updateFavoriteState(holder, video.id)
    }

    /**
     * 显示下拉菜单
     */
    private fun showPopupMenu(view: View, video: VideoIdEntity) {
        val popupMenu = PopupMenu(view.context, view)
        popupMenu.menuInflater.inflate(R.menu.video_options_memu, popupMenu.menu)

        popupMenu.setOnMenuItemClickListener { menuItem ->
            when (menuItem.itemId) {
                R.id.action_report -> {
                    // TODO: 实现举报功能
                    true
                }
                R.id.action_download -> {
                    // TODO: 实现下载功能
                    true
                }
                R.id.action_delete -> {
                    // TODO: 实现删除功能
                    true
                }
                else -> false
            }
        }

        popupMenu.show()
    }

    /**
     * 解析格式化的数字字符串
     */
    private fun parseCount(countText: String): Int {
        return when {
            countText.endsWith("w") -> {
                val number = countText.substring(0, countText.length - 1).toDoubleOrNull() ?: 0.0
                (number * 10000).toInt()
            }
            countText.endsWith("k") -> {
                val number = countText.substring(0, countText.length - 1).toDoubleOrNull() ?: 0.0
                (number * 1000).toInt()
            }
            else -> countText.toIntOrNull() ?: 0
        }
    }

    /**
     * 获取视频列表项的数量
     *
     * @return 列表大小
     */
    override fun getItemCount(): Int = videoList.size

    /**
     * 格式化数字显示，大于等于10000显示为"nw"，大于等于1000显示为"nk"，否则直接显示数字
     *
     * @param count 需要格式化的数字
     * @return 格式化后的字符串
     */
    private fun formatCount(count: Int): String {
        return when {
            count >= 10000 -> "${count / 10000}w"
            count >= 1000 -> "${count / 1000}k"
            else -> count.toString()
        }
    }

    /**
     * 提取字符串的前三位数字
     *
     * @param channelId 频道ID字符串
     * @return 前三位数字，如果不足三位则返回实际数字
     */
    private fun extractFirstFourDigits(channelId: String): Int {
        val digitsOnly = channelId.filter { it.isDigit() }
        return if (digitsOnly.length >= 3) {
            digitsOnly.substring(0, 3).toIntOrNull() ?: 0
        } else {
            digitsOnly.toIntOrNull() ?: 0
        }
    }

    /**
     * 提取字符串的后三位数字
     *
     * @param channelId 频道ID字符串
     * @return 后三位数字，如果不足三位则返回实际数字
     */
    private fun extractLastFourDigits(channelId: String): Int {
        val digitsOnly = channelId.filter { it.isDigit() }
        return if (digitsOnly.length >= 3) {
            digitsOnly.substring(digitsOnly.length - 3).toIntOrNull() ?: 0
        } else {
            digitsOnly.toIntOrNull() ?: 0
        }
    }
}
